#!/usr/bin/env python3
# coding: utf-8
# Copyright 2024 Huawei Technologies Co., Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
# ===========================================================================
import os
import platform
import re
import json
import tarfile
import glob

from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils import common_info, common_utils, venv_installer
from ansible.module_utils.common_info import DeployStatus


class DockerComposeInstaller:

    def __init__(self):
        self.module = AnsibleModule(
            argument_spec=dict(
                tags=dict(type="list", required=True),
                resources_dir=dict(type="str", required=True),
            )
        )
        self.run_tags = self.module.params["tags"]
        self.resources_dir = os.path.expanduser(self.module.params["resources_dir"])
        self.arch = platform.machine()
        self.messages = []

    def _module_failed(self):
        return self.module.fail_json(msg="\n".join(self.messages), rc=1, changed=False)

    def _module_success(self):
        return self.module.exit_json(msg="Install Docker Compose success.", rc=0, changed=True)

    def _find_soft_pkgs(self, filename, pattern):
        pkgs, msgs = common_utils.find_files(os.path.join(self.resources_dir, filename), pattern)
        self.messages.extend(msgs)
        if not pkgs:
            if "auto" in self.run_tags:
                self.module.exit_json(std_out="[ASCEND] can not find Docker Compose package, Docker Compose install skipped", rc=0,
                                      result={DeployStatus.DEPLOY_STATUS: DeployStatus.SKIP},
                                      changed=False)
            else:
                self.messages.append("[ASCEND] can not find Docker Compose package.")
                self._module_failed()

        return pkgs

    def _check_docker_compose_installed(self):
        compose_v2 = False
        compose_path = self.module.get_bin_path("docker-compose", required=False)
        docker_path = self.module.get_bin_path("docker", required=False)
        if not compose_path:
            # 检查 docker compose v2
            rc, out, _ = self.module.run_command([docker_path, "compose", "version"])
            if rc == 0:
                compose_v2 = True
        if compose_path or compose_v2:
            self.messages.append("[ASCEND] Docker Compose is already installed, skip installation.")
            return True
        return False
    
    def install_docker_compose(self):
        # 1. 检查是否已安装
        if self._check_docker_compose_installed():
            self.module.exit_json(std_out="[ASCEND] Docker Compose is already installed, skip installation.", rc=0,
                                      result={DeployStatus.DEPLOY_STATUS: DeployStatus.SKIP},
                                      changed=False)
            return
        # 2. 查找安装包
        compose_pattern = "docker-compose-linux-{}".format(self.arch)
        compose_pkgs = self._find_soft_pkgs("DockerCompose*", compose_pattern)
        compose_pkg = compose_pkgs[0]
        # 3. 复制到 /usr/local/bin/docker-compose
        rc, out, err = self.module.run_command(["cp", compose_pkg, "/usr/local/bin/docker-compose"])
        if rc != 0:           
            self.module.fail_json("[ASCEND][ERROR] Failed to copy Docker Compose binary: {}".format(err))   
        # 4. 赋予执行权限
        compose_path = "/usr/local/bin/docker-compose"
        rc, out, err = self.module.run_command(["chmod", "+x", compose_path])
        if rc != 0:
            self.module.fail_json("[ASCEND][ERROR] Failed to set execute permission for Docker Compose: {}".format(err))
        self.messages.append("Installed Docker Compose successfully.")

    def run(self):
        try:
            self.install_docker_compose()
        except Exception as e:
            self.messages.append(str(e))
            self._module_failed()
        self._module_success()


def main():
    DockerComposeInstaller().run()


if __name__ == "__main__":
    main()
